package oauth

import (
	"fmt"
	"github.com/imroc/req/v3"
	"github.com/tidwall/gjson"
	log "missC/utils/logs"
)

func NewGitee(code string) *Auth {

	return &Auth{
		uri:     "http://localhost:5173/login",
		id:      "06bd1671d5c0f5c3cf87708063a42d14cdcfece60a1b85d91c9c97cc3f24347c",
		secret:  "76ab55dfc5e5bc5273cc1be6b0b40101cac4443a4e9989dd814d89601a500b1a",
		code:    code,
		actoken: "",
	}

}

// 获取code进行gitee验证,得到token
func (a *Auth) Token() {
	res, _ := req.SetQueryParams(map[string]string{
		"grant_type":    "authorization_code",
		"code":          a.code,
		"client_id":     a.id,
		"client_secret": a.secret,
		"redirect_uri":  a.uri,
	}).Post("https://gitee.com/oauth/token")
	fmt.Println(res.String())
	a.actoken = gjson.Get(res.String(), "access_token").String()

}

// 通过token 获取用户的账号
func (a *Auth) GetUser() string {
	//先获取gitee的token
	a.Token()
	//再通过token 得到用户账号
	res, _ := req.SetQueryParams(map[string]string{
		"access_token": a.actoken,
	}).Get("https://gitee.com/api/v5/user")

	//解析json
	giteeUser := gjson.Get(res.String(), "login").String()
	log.Info("三方登陆获取到当前的用户:", giteeUser)
	return giteeUser
}
